﻿using System;
using BLL;
using DAL;
using Ext.Net;
using System.Data;
using Roles;

namespace ERP.Modules
{
    public partial class ExpenditureReason : System.Web.UI.UserControl
    {
        #region[Define]
        private static bool _flag;
        #endregion

        #region[Controller]
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetExpenditureReason();
            }
        }
        //Store
        protected void StoreExpenditureReason_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            GetExpenditureReason();
        }
        protected void StoreAssignedAccountingHave_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearchAccountHave.Text = string.Empty;
            GetAccountLevel2();
        }
        //Button
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            ClearText();
            WindowsExpenditureReason.Show();
        }
        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grExpenditureReason.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    ClearText();
                    GetExpenditureReasonEdit(int.Parse(row.RecordID));
                    WindowsExpenditureReason.Show();
                    sm.UpdateSelection();
                }
        }
        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grExpenditureReason.GetSelectionModel() as CheckboxSelectionModel;
            if (sm != null)
                foreach (SelectedRow row in sm.SelectedRows)
                {
                    try
                    {
                        var obj = new EtExpenditureReason { ID = int.Parse(row.RecordID) };
                        BllExpenditureReason.DeleteExpenditureReason(obj);
                        if (obj.Msg == 0)
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Có chứng từ liên quan.Vui lòng xoá chứng từ trước khi xoá phương thức !");
                    }
                    catch (Exception)
                    {
                        HTML.clsFormat.Alert_ERROR("Thông Báo", "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                    }
                }
            GetExpenditureReason();
        }
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            Insert();
        }
        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsExpenditureReason.Close();
        }
        protected void btnHave_Click(object sender, DirectEventArgs e)
        {
            _flag = true;
            GetAccountLevel2();
            WindowsAccounting.Show();
        }
        protected void btnDebt_Click(object sender, DirectEventArgs e)
        {
            _flag = false;
            GetAccountLevel2();
            WindowsAccounting.Show();
        }
        //Double_Click
        protected void ExpenditureReasonDblClick(object sender, DirectEventArgs e)
        {
            ClearText();
            int id = int.Parse(e.ExtraParams["ID"]);
            GetExpenditureReasonEdit(id);
            WindowsExpenditureReason.Show();
        }
        //Cell_Click
        protected void CellAssignedAccountingHave_Click(object sender, DirectEventArgs e)
        {
            var sm = grAssignedAccountingHave.GetSelectionModel() as CellSelectionModel;
            if (sm != null)
            {
                var id = sm.SelectedCell.RecordID;
                CellClick(int.Parse(id));
            }
            if (sm != null)
            {
                sm.Clear();
                sm.UpdateSelection();
            }
            WindowsAccounting.Close();
        }
        //Search
        protected void Search_Event(object sender, DirectEventArgs e)
        {
            var _clsReceiptReason = new BllExpenditureReason();
            var dtSearch = _clsReceiptReason.GetExpenditureReason(txtSearch.Text);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                StoreExpenditureReason.DataSource = dtSearch;
                StoreExpenditureReason.DataBind();
            }
            else
            {
                grExpenditureReason.GetStore().RemoveAll();
            }
        }
        protected void AccountingHaveSearch_Event(object sender, DirectEventArgs e)
        {
            var _clsAccountLv2 = new BllDalAssignedAccountLevel2();
            var dtSearch = _clsAccountLv2.AssignedAccountLevel2Get(txtSearch.Text);
            if (dtSearch != null && dtSearch.Rows.Count > 0)
            {
                StoreAssignedAccountLevelHave.DataSource = dtSearch;
                StoreAssignedAccountLevelHave.DataBind();
            }
            else
            {
                grAssignedAccountingHave.GetStore().RemoveAll();
            }
        }
        #endregion

        #region[Method]
        private void GetExpenditureReason()
        {
            var _clsExpenditureReason = new BllExpenditureReason();
            var _dtExpenditureReason = _clsExpenditureReason.GetExpenditureReason(txtSearch.Text);
            if (_dtExpenditureReason != null && _dtExpenditureReason.Rows.Count > 0)
            {
                StoreExpenditureReason.DataSource = _dtExpenditureReason;
                StoreExpenditureReason.DataBind();
            }
            else
            {
                grExpenditureReason.GetStore().RemoveAll();
            }
        }
        private void GetExpenditureReasonEdit(int id)
        {
            var _clsExpenditureReason = new BllExpenditureReason();
            var _dtExpenditureReasonEdit = _clsExpenditureReason.GetExpenditureReasonEdit(id);
            if (_dtExpenditureReasonEdit != null && _dtExpenditureReasonEdit.Rows.Count > 0)
            {
                txtReceiptReason_ID.Text = _dtExpenditureReasonEdit.Rows[0]["ID"].ToString();
                txtIDHave.Text = _dtExpenditureReasonEdit.Rows[0]["IDAccountLevel2_Have"].ToString();
                txtIDDebt.Text = _dtExpenditureReasonEdit.Rows[0]["IDAccountLevel2_Debt"].ToString();
                txtReceiptReason_Alias.Text = _dtExpenditureReasonEdit.Rows[0]["ReceiptReasonCode"].ToString();
                txtReceiptReason_Name.Text = _dtExpenditureReasonEdit.Rows[0]["ReceiptReasonName"].ToString();
                txtHave.Text = _dtExpenditureReasonEdit.Rows[0]["AccountLevel2_Name_Code_Have"].ToString();
                txtDebt.Text = _dtExpenditureReasonEdit.Rows[0]["AccountLevel2_Name_Code_Debt"].ToString();
                txtReceiptReason_Note.Text = _dtExpenditureReasonEdit.Rows[0]["Note"].ToString();
            }
        }
        private void GetAccountLevel2()
        {
            var _clsAccountLv2 = new BllDalAssignedAccountLevel2();
            var _dtGetAccountLevel2 = _clsAccountLv2.AssignedAccountLevel2Get(txtSearch.Text);
            if (_dtGetAccountLevel2 != null && _dtGetAccountLevel2.Rows.Count > 0)
            {
                StoreAssignedAccountLevelHave.DataSource = _dtGetAccountLevel2;
                StoreAssignedAccountLevelHave.DataBind();
            }
            else
            {
                grAssignedAccountingHave.GetStore().RemoveAll();
            }
        }
        private void GetAccountLevel2Have(int id)
        {
            var _clsAccountLv2 = new BllDalAssignedAccountLevel2();
            var _dtGetAccountLevel2Edit = _clsAccountLv2.AssignedAccountLevel2GetEdit(id);
            if (_dtGetAccountLevel2Edit != null && _dtGetAccountLevel2Edit.Rows.Count > 0)
            {
                txtIDHave.Text = _dtGetAccountLevel2Edit.Rows[0]["IDAccountLevel2"].ToString();
                txtHave.Text = _dtGetAccountLevel2Edit.Rows[0]["AccountLevel2_Name_Code"].ToString();
            }
        }
        private void GetAccountLevel2Debt(int id)
        {
            var _clsAccountLv2 = new BllDalAssignedAccountLevel2();
            var _dtGetAccountLevel2Edit = _clsAccountLv2.AssignedAccountLevel2GetEdit(id);
            if (_dtGetAccountLevel2Edit != null && _dtGetAccountLevel2Edit.Rows.Count > 0)
            {
                txtIDDebt.Text = _dtGetAccountLevel2Edit.Rows[0]["IDAccountLevel2"].ToString();
                txtDebt.Text = _dtGetAccountLevel2Edit.Rows[0]["AccountLevel2_Name_Code"].ToString();
            }
        }
        private void CellClick(int id)
        {
            if (_flag)
            {
                GetAccountLevel2Have(id);
            }
            else
            {
                GetAccountLevel2Debt(id);
            }
        }
        private bool CheckInsert()
        {
            var check = false;
            var _clsExpenditureReasonCheck = new BllExpenditureReason();
            var dtCheck = _clsExpenditureReasonCheck.GetExpenditureReason(string.Empty);
            if (dtCheck != null && dtCheck.Rows.Count > 0)
            {
                foreach (DataRow dr in dtCheck.Rows)
                {
                    if (txtReceiptReason_ID.Text != dr["ID"].ToString())
                    {
                        if (txtReceiptReason_Alias.Text == dr["ReceiptReasonCode"].ToString())
                        {
                            check = true;
                            HTML.clsFormat.Alert_ERROR("Thông Báo", "Mã loại phiếu thu này đã tồn tại !");
                        }
                    }
                }
            }
            return check;
        }
        private void Insert()
        {
            if (String.IsNullOrEmpty(txtReceiptReason_ID.Text))
            {
                InsertValue();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                }
                else
                {
                    UpdateValue();
                }
            }
        }
        private void InsertValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new EtExpenditureReason
                    {
                        ReceiptReasonCode = txtReceiptReason_Alias.Text,
                        ReceiptReasonName = txtReceiptReason_Name.Text,
                        Debt = String.IsNullOrEmpty(txtIDDebt.Text) ? (int?)null : int.Parse(txtIDDebt.Text),
                        Have = String.IsNullOrEmpty(txtIDHave.Text) ? (int?)null : int.Parse(txtIDHave.Text),
                        Note = txtReceiptReason_Note.Text,
                        IsActive = chkIsActive.Checked
                    };
                    BllExpenditureReason.InsertExpenditureReason(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công !");
                    GetExpenditureReason();
                    ClearText();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        private void UpdateValue()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new EtExpenditureReason
                    {
                        ID = int.Parse(txtReceiptReason_ID.Text),
                        ReceiptReasonCode = txtReceiptReason_Alias.Text,
                        ReceiptReasonName = txtReceiptReason_Name.Text,
                        Debt = String.IsNullOrEmpty(txtIDDebt.Text) ? (int?)null : int.Parse(txtIDDebt.Text),
                        Have = String.IsNullOrEmpty(txtIDHave.Text) ? (int?)null : int.Parse(txtIDHave.Text),
                        Note = txtReceiptReason_Note.Text,
                        IsActive = chkIsActive.Checked
                    };
                    BllExpenditureReason.UpdateExpenditureReason(obj);
                    HTML.clsFormat.Alert_INFO("Thông Báo", "Cập nhật thành công !");
                    GetExpenditureReason();
                }
            }
            catch (Exception ex)
            {
                HTML.clsFormat.Alert_ERROR("Lỗi", ex.Message);
            }
        }
        #endregion

        #region[Clear-Text]
        private void ClearText()
        {
            txtReceiptReason_Alias.Text = string.Empty;
            txtReceiptReason_Name.Text = string.Empty;
            txtDebt.Text = string.Empty;
            txtIDDebt.Text = string.Empty;
            txtHave.Text = string.Empty;
            txtIDHave.Text = string.Empty;
            txtReceiptReason_ID.Text = string.Empty;
            txtReceiptReason_Note.Text = string.Empty;
        }
        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.ExpenditureReason, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelExpenditureReason.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.ExpenditureReason, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion
    }
}